<?php
/**
 * xushuhui
 * 2017/8/7
 * 10:34
 */

namespace app\index\controller;


use app\index\model\Order;
use app\index\model\Recharge;
use app\index\model\User;
use app\index\service\WxNotify;
use app\index\service\WechatPay;
use think\Controller;
use think\Exception;
use think\Log;
use think\Url;

class Pay extends Controller
{
	//支付通知
	public function notify()
	{
		$data = file_get_contents("php://input");
		$notifyInfo = (array) simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);

		if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS'){
			try {
				$order = Order::where('orderNo', $notifyInfo['out_trade_no'])->find();

				if($order->getData('status') == 1){
					$this->updateOrderStatus($order->id, 2);
				}
				return true;
			} catch (Exception $ex) {
				LogWrite($ex);
				// 如果出现异常，向微信返回false，请求重新发送通知
				return false;
			}
		}
		return true;
	}
	private function updateOrderStatus($orderID, $status)
	{
		return Order::where('id', '=', $orderID)
			->update(['status' => $status]);
	}
	//定时任务
	public function crontab()
	{
		$orderObj = Order::where('status','=',1)->with(['wxuser','plan'])->group('uid')->select();
		$orders = $orderObj->toArray();
		$template_id = config('wx.template_id');
		$res = [];
		$time = date('Y-m-d H:i:s',time());
		foreach($orders as $k=>$v){
			$JumpUrl = Url::build('Index/My/pay',['id'=>$v['id']],true,true);
			$data = array(
					'first'=>array('value'=>'您好，请支付','color'=>'#173177'),
					'keyword1'=>array('value'=>$v['orderNo'],'color'=>'#173177'),
					'keyword2'=>array('value'=>$v['money'],'color'=>'#173177'),
					'keyword3'=>array('value'=>$v['plan']['money'],'color'=>'#173177'),
					'remark'=>array('value'=>"感谢您的使用,时间$time",'color'=>'#173177'),
			);
			$res[] = WechatPay::sendWxMessage($v['wxuser']['openid'],$template_id,$JumpUrl,$data);
		}
		return true;
	}
	// 充值成功通知
	public function recharge()
	{
		$data = file_get_contents("php://input");
		$notifyInfo = (array) simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
		if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS'){
			try {
				$recharge = Recharge::where('orderNo',$notifyInfo['out_trade_no'])->field('id,uid,money,status')->find();
				if($recharge['status'] == 1){
					// 更新充值记录支付状态
					Recharge::where('id','=',$recharge['id'])->update(['status'=>2]);
					// 修改用户余额
					$this->updateUserMoney($recharge['uid'],$recharge['money']);
					return true;
				}
			}catch (Exception $ex) {
				Log::error($ex);
				// 如果出现异常，向微信返回false，请求重新发送通知
				return false;
			}

		}
		return true;
	}
	//更新用户余额
	private function updateUserMoney($uid=0,$rechargeMoney=0)
	{
		$usermoney = User::get($uid)['money'];
		$money = $usermoney + $rechargeMoney;
		$res = User::where('id','=',$uid)->update(['money' => $money]);
		return $res;
	}

}